package com.asp;

/**
 * author:          ndg
 * date:            2024/3/29
 */

import com.asp.utils.SensitiveWordUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SensitiveWordFilter {

    private Pattern pattern;

    public SensitiveWordFilter(List<String> sensitiveWords) {
        StringBuilder sb = new StringBuilder();
        for (String word : sensitiveWords) {
            sb.append("|").append(Pattern.quote(word));
        }
        String regex = sb.substring(1);  // 去掉开头的"|"
        pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    }

    public String filter(String text) {
        Matcher matcher = pattern.matcher(text);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "***");  // 将匹配到的敏感词替换为"***"
        }
        matcher.appendTail(sb);  // 添加剩余部分到结果中
        return sb.toString();
    }

    public static void main(String[] args) {

        String text = SensitiveWordUtils.filter("操  ssss  sb  原神");
        System.out.println(text);
    }

}